// 恢复二叉搜索树

package Leetcode;

import java.util.ArrayList;
import java.util.List;

class solution_099 {
    public void recoverTree(TreeNode root) {
        List<TreeNode> inorder = new ArrayList<>();
        InorderTraverse(inorder, root);
        int exchange1 = 0;
        for (int i = 0; i < inorder.size() - 1; i++) {
            // 找到第一个大于后面的结点
            if (inorder.get(i).val > inorder.get(i + 1).val) {
                exchange1 = i;
                break;
            }
        }
        // 找到exchange1之后最小的那个数
        int exchange2 = exchange1 + 1;
        TreeNode min = inorder.get(exchange2);
        for (int j = exchange1 + 2; j < inorder.size(); j++) {
            if (inorder.get(j).val < min.val) {
                min = inorder.get(j);
                exchange2 = j;
            }
        }
        //交换两个数字
        int temp = inorder.get(exchange1).val;
        inorder.get(exchange1).val = inorder.get(exchange2).val;
        inorder.get(exchange2).val = temp;
    }

    public void InorderTraverse(List<TreeNode> inorder, TreeNode root) {
        if (root != null) {
            InorderTraverse(inorder, root.left);
            inorder.add(root);
            InorderTraverse(inorder, root.right);
        }
    }
}

public class Solution099 {

}
